<?php
class Server {
  public static function submit_obj($orm, $sys, $inst, $is_iframe) {
    $req = json_decode(Utils::get_param('req', '[]'));
    
    if (isset($req->id) && $req->id != 0) {
      $orm->update('pb_colg_enrollment', $req);
      if ($req->__fl_update_personal == 1) {
        $opts = new stdClass();
        $opts->cd = 't.id = :v1';
        $opts->cdv = array(':v1' => $req->student_id);
        $rslt = $orm->get('pb_colg_student', NULL, NULL, NULL, NULL, $opts)->d;
        if (count($rslt) > 0) {
          if (strcmp($rslt[0]->visa_expiry, $req->fl_visa_expiry) < 0) {
            $rslt[0]->visa_expiry = $req->fl_visa_expiry;
            $rslt[0]->visa_type = $req->fl_visa_type;
          }
          if (strcmp($rslt[0]->passport_expiry, $req->fl_passport_expiry) < 0) {
            $rslt[0]->passport_expiry = $req->fl_passport_expiry;
            $rslt[0]->passport_no = $req->fl_passport_no;
          }
          if (strcmp($rslt[0]->insurance_expiry, $req->fl_insurance_expiry) < 0) {
            $rslt[0]->insurance_expiry = $req->fl_insurance_expiry;
            $rslt[0]->insurance_com = $req->fl_insurance_com;
            $rslt[0]->insurance_number = $req->fl_insurance_number;
          }
          $orm->update('pb_colg_student', $rslt[0]);
        }
      }
    }
    
    if (isset($req->__pg)) {
      $opts = new stdClass();
      $opts->cd = 't.is_paid = :v1 AND t.is_trial = :v3';
      $opts->cdv = array(':v1' => 1, ':v3' => 0);
      $req->__objs = $orm->get('pb_colg_enrollment', 't.id', 'DESC', $req->__pg, SIZE, $opts);
    }
    
    echo json_encode($req);
  }
  
  public static function get_obj($orm, $sys, $inst, $is_iframe) {
    $req = json_decode(Utils::get_param('req', '[]'));
    
    $opts = new stdClass();
    $opts->cd = 't.id = :v1';
    $opts->cdv = array(':v1' => $req->id);
    $opts->sel = 't.*, t1.passport_no AS __passport_no, t1.passport_expiry AS __passport_expiry';
    $opts->jt = 'LEFT JOIN pb_colg_student AS t1 ON t1.id = t.student_id';
    $res = $orm->get('pb_colg_enrollment', NULL, NULL, NULL, NULL, $opts)->d;
    if (count($res) > 0) {
      $opts = new stdClass();
      $opts->cd = 't.student_id = :v1 AND t.id != :v2 AND t.start_academic < :v3';
      $opts->cdv = array(':v1' => $res[0]->student_id, ':v2' => $res[0]->id, ':v3' => $res[0]->start_academic);
      $res[0]->__history = $orm->get('pb_colg_enrollment', 't.start_academic', 'DESC', NULL, NULL, $opts)->d;
    }
    echo json_encode($res);
  }
}
?>